package com.freemarker.config;

import freemarker.template.TemplateException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Map;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/4/17 12:24
 * @since JDK 1.8
 */
@Component
public class FreeMarkerConfig implements ApplicationContextAware {

    @Autowired
    protected freemarker.template.Configuration configuration;

    ApplicationContext applicationContext ;

    @PostConstruct
    public void setSharedVariable() throws IOException, TemplateException {
        // 根据注解获取bean ,key is bean name ,value is bean object
        Map<String, Object> map = this.applicationContext.getBeansWithAnnotation(FreemarkerComponent.class);
        for (String key : map.keySet()) {
            configuration.setSharedVariable(key, map.get(key));
        }
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }
}
